package com.ding.easycontroller.file.impl;

import com.ding.easycontroller.file.PluginFile;
import com.ding.easycontroller.file.PluginFilePathHolder;
import com.ding.easycontroller.utils.ClassLoadUtils;
import com.ding.easycontroller.utils.FileUtils;
import easycontroller.plugin.Plugin;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;

@Component
public class PluginFileImpl implements PluginFile {

    private File root;

    PluginFileImpl(PluginFilePathHolder holder) {


        File parent = holder.getRoot();
        File file = new File(parent, "plugin");
        root = file;
        if (!file.exists()) {
            if (!file.mkdirs()) {
                throw new RuntimeException("路径创建失败" + file.getAbsolutePath());
            } else {
                try {
                    InputStream inputStream = new ClassPathResource("plugin/basePlugins-1.0-SNAPSHOT-jar-with-dependencies.jar").getInputStream();
                    File out = new File(root, "easy-controller-base-plugins.jar");
                    FileOutputStream fileOutputStream = new FileOutputStream(out);
                    FileUtils.copyStream(inputStream, fileOutputStream);
                    inputStream.close();
                    fileOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @Override
    public List<Plugin> loadAllPlugins() {
        List<Plugin> r = new ArrayList<>();
        File[] files = root.listFiles();


        if (files != null) {
            for (File file : files) {
                if (file.getName().endsWith(".jar")) {
                    List<Class<?>> classes = ClassLoadUtils.loadClassFromJarFile(file);

                    List<Plugin> plugins = instancePlugins(classes);
                    r.addAll(plugins);
                }
            }
        }
        return r;
    }


    private List<Plugin> instancePlugins(List<Class<?>> classes) {
        List<Plugin> plugins = new ArrayList<>();
        for (Class<?> aClass : classes) {
            Class<?> superclass = aClass.getSuperclass();
            if (superclass == Plugin.class) {
                try {
                    Constructor constructor = aClass.getConstructor();
                    plugins.add((Plugin) constructor.newInstance());
                } catch (Exception ignore) {
                    System.err.println(aClass.getName() + "不可见或没有无参构建函数");
                }
            }
        }
        return plugins;

    }

}
